package admin

import (
	"baokaobang/conf"
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"strings"

	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

type HighSchool struct {
	Ctx iris.Context
}

type HighSchoolCreate struct {
	Id         string `json:"id"`
	ProvinceId int    `json:"provinceId"`
	CityId     int    `json:"cityId"`
	DistrictId int    `json:"districtId"`
	Nature     int    `json:"nature"`
	MType      int    `json:"mType"`
	Name       string `json:"name"`
}

type HighSchoolExcelCreate struct {
	ExcelUrl string `json:"excelUrl"`
}

type HighSchoolListParam struct {
	ProvinceId int `json:"provinceId"`
	CityId     int `json:"cityId"`
	PerPage    int `json:"perPage"`
	CurPage    int `json:"curPage"`
}

func (c *HighSchool) OptionsAll() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *HighSchool) PostAll() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	highSchoolList := make([]models.HighSchool, 0)
	err = db.Where("id > ?", 0).Find(&highSchoolList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("获取所有高中列表失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "成功获取所有高中列表", highSchoolList)
}

func (c *HighSchool) OptionsExcel() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *HighSchool) PostExcel() interface{} {
	highSchoolExcelCreate := HighSchoolExcelCreate{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接受请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &highSchoolExcelCreate)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("参数解析出错:%s", err.Error()), "")
	}

	if len(highSchoolExcelCreate.ExcelUrl) <= 0 {
		return utils.CommonRes(1000, "请上传excel文件", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	sess := db.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库事务开启失败：%s", err.Error()), "")
	}

	filePath := fmt.Sprintf("%s%s", conf.UploadPrefix.Backend, highSchoolExcelCreate.ExcelUrl)
	f, err := excelize.OpenFile(filePath)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("上传的文件无法打开:%s", err.Error()), "")
	}

	cityName := ""
	
	natureMap := map[string]int{
		"公办": 1,
		"民办": 2,
	}

	typeMap := map[string]int{
		"省重点": 1,
		"省示范": 2,
		"市示范": 3,
		"普通":  4,
		"职高":  5,
	}

	sheetList := f.GetSheetMap()
	for _, sheet := range sheetList {
		rows := f.GetRows(sheet)
		for i, row := range rows {
			if i == 0 {
				continue
			}

			tmpCityName := strings.TrimSpace(row[0])
			if len(tmpCityName) > 0 {
				cityName = tmpCityName
			}

			if len(cityName) <= 0 {
				return utils.CommonRes(1000, fmt.Sprintf("%s不知道属于哪个市", row[1]), "")
			}

			city := new(models.Region)
			ok, _ := sess.Where("name = ?", cityName).Get(city)
			if !ok {
				return utils.CommonRes(1000, fmt.Sprintf("%s不存在于系统中", cityName), "")
			}

	
			highSchool := new(models.HighSchool)
			highSchool.ProvinceId = city.ParentId
			highSchool.CityId = city.Id
			// highSchool.DistrictId = city
			highSchool.Name = row[1]
			highSchool.MType = typeMap[strings.TrimSpace(row[3])]
			highSchool.Nature = natureMap[strings.TrimSpace(row[4])]
			_, err = sess.InsertOne(highSchool)
			if err != nil {
				return utils.CommonRes(1000, fmt.Sprintf("数据导入失败：%s", err.Error()), "")
			}
		}
	}
	sess.Commit()

	return utils.CommonRes(20000, "数据导入成功", "")
}

func (c *HighSchool) OptionsList() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *HighSchool) PostList() interface{} {
	highSchoolListParam := HighSchoolListParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &highSchoolListParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	start := (highSchoolListParam.CurPage - 1) * highSchoolListParam.PerPage
	highSchoolList := make([]models.HighSchoolObj, 0)
	sess := db.Table(new(HighSchool)).Alias("hs").
		Join("LEFT", []string{"region", "p"}, "hs.province_id = p.id").
		Join("LEFT", []string{"region", "c"}, "hs.city_id = c.id").
		Join("LEFT", []string{"region", "d"}, "hs.district_id = d.id").
		Where("isnull(hs.deleted)=1").
		Limit(highSchoolListParam.PerPage, start)
	if highSchoolListParam.ProvinceId > 0 {
		sess = sess.Where("hs.province_id = ?", highSchoolListParam.ProvinceId)
	}
	if highSchoolListParam.CityId > 0 {
		sess = sess.Where("hs.city_id = ?", highSchoolListParam.CityId)
	}
	err = sess.Find(&highSchoolList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取高中列表:%s", err.Error()), "")
	}

	countSess := db.Where("id > ?", 0)
	if highSchoolListParam.ProvinceId > 0 {
		countSess = countSess.Where("province_id = ?", highSchoolListParam.ProvinceId)
	}
	if highSchoolListParam.CityId > 0 {
		countSess = countSess.Where("city_id = ?", highSchoolListParam.CityId)
	}
	total, err := countSess.Count(new(models.HighSchool))
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取高中列表:%s", err.Error()), "")
	}

	for i, item := range highSchoolList {
		highSchoolList[i].HighSchool.NatureShow = models.HighSchoolNature[item.HighSchool.Nature]
		highSchoolList[i].HighSchool.TypeShow = models.HighSchoolType[item.HighSchool.MType]
	}

	data := map[string]interface{}{
		"total": total,
		"list":  highSchoolList,
	}

	return utils.CommonRes(20000, "成功获取高中列表", data)
}

func (c *HighSchool) OptionsEdit() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *HighSchool) PostEdit() interface{} {
	highSchoolCreate := HighSchoolCreate{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &highSchoolCreate)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(highSchoolCreate.Id) <= 0 {
		return utils.CommonRes(1000, "请提供高中id", "")
	}
	if len(highSchoolCreate.Name) <= 0 {
		return utils.CommonRes(1000, "请输入高中名称", "")
	}
	if highSchoolCreate.ProvinceId <= 0 {
		return utils.CommonRes(1000, "请选择省", "")
	}
	if highSchoolCreate.CityId <= 0 {
		return utils.CommonRes(1000, "请选择市", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	updateData := map[string]interface{}{
		"province_id": highSchoolCreate.ProvinceId,
		"city_id":     highSchoolCreate.CityId,
		"district_id": highSchoolCreate.DistrictId,
		"nature":      highSchoolCreate.Nature,
		"m_type":      highSchoolCreate.MType,
		"name":        highSchoolCreate.Name,
	}

	_, err = db.Table(new(models.HighSchool)).ID(highSchoolCreate.Id).Update(updateData)
	if err != nil {
		return utils.CommonRes(1000, "操作失败", "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}

func (c *HighSchool) OptionsDetail() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *HighSchool) PostDetail() interface{} {
	editParam := utils.EditParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &editParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(editParam.Id) <= 0 {
		return utils.CommonRes(1000, "请提供位次id", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	highSchool := new(models.HighSchool)
	ok, err := db.ID(editParam.Id).Get(highSchool)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("信息获取失败:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "信息获取失败", "")
	}

	return utils.CommonRes(20000, "信息获取成功", highSchool)
}

func (c *HighSchool) OptionsDel() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *HighSchool) PostDel() interface{} {
	delParam := utils.DelParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接受请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &delParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("参数解析出错：%s", err.Error()), "")
	}

	if len(delParam.Ids) <= 0 {
		return utils.CommonRes(1000, "请提供要删除项的id", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	ids := strings.Split(delParam.Ids, ",")
	for _, id := range ids {
		highSchool := new(models.HighSchool)
		db.ID(id).Get(highSchool)
		db.ID(id).Delete(highSchool)
	}

	return utils.CommonRes(20000, "操作成功", "")
}
